<template>
    <div class="login-container">
        <div class="login-box">
            <img src="../../assets/image/星.png" alt="Avatar" class="avatar" />
            <div class="rating">
                <span class="star" v-for="n in 5" :key="n">*</span>
            </div>

            <!-- 密码功能 -->
            <el-form ref="formRef" :rules="data.rules" :model="data" v-if="data.isShow" label-width="auto"
                style="max-width: 580px; margin-left: 80px;">
                <el-form-item label="原密码：" prop='originalPassword' style="margin-top: 30px;">
                    <el-input v-model="data.originalPassword" placeholder="原密码：" show-password />
                </el-form-item>

                <el-form-item label="新密码：" prop='password' style="margin-top: 30px;">
                    <el-input v-model="data.password" placeholder="新密码：" show-password />
                </el-form-item>

                <el-form-item label="确认密码：" prop='affirmPassword' style="margin-top: 30px;">
                    <el-input v-model="data.affirmPassword" placeholder="确认密码：" show-password />
                </el-form-item>
            </el-form>

            <el-form v-if="!data.isShow" label-width="auto" style="max-width: 580px; margin-left: 80px;">
                <el-form-item label="短信验证码：" style="margin-top: 30px;">
                    <el-input v-model="data.verificationCode" placeholder="请输入手机验证码" />
                </el-form-item>
            </el-form>

            <el-button v-if="data.isShow" type="primary" style="margin-left: 20px; width: 500px; margin-top: 20px;"
                id="makesure">确 认</el-button>
            <el-button v-if="!data.isShow" type="warning" style="margin-left: 20px; width: 500px; margin-top: 20px;"
                @click="resetPassword">重 置</el-button>
            <br><span style="cursor: pointer;font-size: 12px;color: #005980;" @click="reset">{{ data.isShow ?
                data.state1 : data.state2 }}</span>
        </div>
    </div>
</template>

<script setup>
import { checkPassword, resetUserPassword, selectPassword, sendCode, updateUserPassword } from '@/api/edit';
import router from '@/router';
import { useUserStore } from '@/stores/user';
import { ElMessage, ElMessageBox } from 'element-plus';
import { nextTick, reactive, ref } from 'vue';

const data = reactive({
    originalPassword: '', // 原密码 
    password: '', //新密码
    affirmPassword: '', // 确认新密码
    verificationCode: '', // 短信验证码
    isShow: true,
    state1: '已有账号,忘记密码',
    state2: '返回',
    code: null, // 存放手机短信验证码

    passwordError: '',

    rules: {
        originalPassword: [
            { required: true, message: '请输入原密码', trigger: 'blur' }
        ],
        password: [
            { required: true, message: '请输入账号密码', trigger: 'blur' },
            { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ],
        affirmPassword: [
            { required: true, message: '请再次输入密码', trigger: 'blur' },
            {
                validator: (rule, value, callback) => {
                    if (value !== data.password) {
                        callback(new Error('两次输入的密码不一致'));
                    } else {
                        callback();
                    }
                },
                trigger: 'blur'
            }
        ],

    },
})

const formRef = ref()

const userObj = useUserStore() //大菠萝的数据存放

nextTick(() => {
    const btn = document.querySelector('#makesure')
    btn.addEventListener('click', thorttle(makeSure, 3000))
})


//节流函数
const thorttle = (fn, time) => {
    let timer = false;
    return () => {
        if (timer === false) {
            timer = setTimeout(() => {
                fn()
                timer = false;
            }, time)
        }
    }
}


const makeSure = async () => {
    formRef.value.validate((valid) => {
        if (valid) {
            const user = {}
            user.id = userObj.user.id
            user.password = data.affirmPassword
             checkPassword(userObj.user.id, data.originalPassword).then(res => {              
                if (res.data.msg == '原密码错误') {
                    ElMessage.info('原密码与新密码不一致')
                } else {
                     updateUserPassword(user).then(res => {
                        if (res.data.code == 200) {
                            ElMessage.success('修改成功');
                            router.push('/login');
                        } else {
                            ElMessage.error('修改失败');
                        }
                    })
                }
            })
        } else {
            ElMessage.error('表单验证失败');
            return false;
        }
    })
}


//重置密码
const resetPassword = () => {
    if (data.verificationCode != data.code) {
        ElMessage.error('手机验证码输入有误!')
    } else {
        ElMessageBox.confirm('重置密码回到最新状态愿', '删除', { type: 'warning', cancelButtonText: '取消', confirmButtonText: '确认', showClose: false }).then(() => {
            resetUserPassword(userObj.user.id).then(res => {
                if (res.data.code != 200) {
                    ElMessage.error('重置失败')
                } else {
                    router.push('/login')
                }
            })
        }).catch()
    }
}

const reset = () => {
    data.isShow = !data.isShow
    console,console.log(userObj.user.phone);
    
    sendCode(userObj.user.phone).then(res => {
        data.code = res.data.message
    })
}

</script>

<style scoped>
.login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 83vh;
    background-color: #f0f2f5;
}

.login-box {
    background-color: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    text-align: center;
    height: 500px;
    width: 800px;
}

.avatar {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    margin-bottom: 20px;
}

.rating {
    margin: 10px 0;
    color: gold;
}

.star {
    margin: 0 5px;
}

input[type="password"] {
    width: 100%;
    padding: 10px;
    margin: 10px 0;
    border: 1px solid #ccc;
    border-radius: 4px;
}
</style>